import { View, Image, Text, CoverImage, RichText } from '@tarojs/components'
import { useState, useEffect } from 'react'
import LgButton from '@/pages/components/button'
import LgInput from '@/pages/components/input'
import LgCell from '@/pages/components/cell'
import LgSwitch from '@/pages/components/switch'
import { LgSlide } from '@/pages/components/slides'
import { LgPopLayer } from '@/pages/components/popLayer'
import Header from '@/pages/components/navCustomBar'
import Taro from '@tarojs/taro'
import Proxy from '@/network/proxy'
import { requestSystemUrl } from '@/network/baseUrl'
import { HttpGet, HttpPut, HttpPost, HttpDelete } from '@/network/servers'
import { getBaseUrl } from '@/network/baseUrl'
import Utils from '@/utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import '../../images/public/style.css'
import './index.scss'
import { isBuffer, values } from 'lodash'
import MyEditor from './MyEditor'
import PrPopInput from '../popInput'
import { Dialog } from 'antd-mobile'

const browserController = getBrowserController()
const net = getNet()
const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getNowEnvironment,
  getNowToken,
  RemoveHTML,
  getQueryVariable,
  chooseFile,
  replaceHost
} = Utils


const requireContext = require.context("../../images/fileIcon", true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
  let str = item.replace('./', "").replace('.svg', "")
  fileObj[str] = svgs[index]
})


function App(props) {

  let {
    noticeAddr,
    userInfo,
    env,
    baseUrl,
    systemInfo1
  } = props
  console.log(props, 'props');

  const getToken = () => {
    if (getQueryVariable('env') == 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }


  const [detail, setDetail] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [imgList, setImgList] = useState([]);

  const [newsId, setNewsId] = useState("");
  const [taskId, setTaskId] = useState('')

  const [isRead, setIsRead] = useState(0);
  const [type, setType] = useState('0');
  const [height, setHeight] = useState(0);

  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [cover, setCover] = useState('')
  //2023
  const [contentPageList, setContentPageList] = useState<any>([])
  const [typeList, setTypeList] = useState([])
  const [visible, setVisible] = useState(false)
  const [typeId, setTypeId] = useState('')
  const [typeName, setTypeName] = useState('')

  const [systemInfo, setSystemInfo] = useState(systemInfo1)
  const [toEdu, setToEdu] = useState(false)

  const [inputPopOpen, setInputPopOpen] = useState(false)//2023-10-08 增加类型修改功能
  const [inputPopOpenNew, setInputPopOpenNew] = useState(false)//2023-10-09 新增类型
  const [oldValue, setOldValue] = useState('')//2023-10-08 类型旧名称
  const [oldItem, setOldItem] = useState('')//2023-10-08 保存所修改的某条类型

  const [sensetiveData, setSensetiveData] = useState([])

  const getCommonData = () => {
    if (Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram') {
      // 小程序端的h5
      if (!baseUrl) {
        // 直接跳转当前页面

      } else {
        console.log('小程序');

        //应用内跳转
        let instance = Taro.getCurrentInstance()
        if (instance.router?.params) {
          let params = instance.router.params
          let id = params.id
          if (!id) return;
          // console.log(params);
          setIsRead(isRead)
          setNewsId(id)

          let url = "/api/news/info//edit/detailed"
          HttpGet({
            url,
            data: {
              newsId: id,
            }
          }).then(res => {
            if (res.code == 200 && res.data) {
              let data = res.data
              console.log(data.newsCoverPath, 'data.newsCoverPath');

              setTitle(data.newsTitle)
              // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
              setContent(data.newsContent)
              setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
              setTypeId(data.newsTypeId)
              setTypeName(data.newsTypeName)
              let attachments = res.data.newsAttachmentVoList
              if (attachments && attachments.length !== 0) {
                let imgArr = [], fileArr = [];
                attachments.map(item => {
                  let fileType = Utils.getFileType(item?.attachmentName)
                  if (fileType == 'img') {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    imgArr.push(item)
                  } else {
                    item.url = item.attachmentUrl
                    item.size = item.attachmentSize
                    item.fileName = item.attachmentName
                    fileArr.push(item)
                  }
                })

                setFileList(fileArr)
                setImgList(imgArr)
              }
              setIsRead(res.data.readStatus)
              setDetail(res.data)
            } else {
              Taro.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      }
    } else {
      // app内 1.应用内跳转(不需要获取通知地址和用户信息) 2.直接跳转
      let instance = Taro.getCurrentInstance()

      const browserController = getBrowserController()
      let height = browserController.getStatusBarHeight()
      setHeight(height)
      if (instance.router?.params) {
        let params = instance.router.params
        let id = params.id
        if (!id) return;
        // console.log(params);

        setIsRead(isRead)
        setNewsId(id)

        HttpGet({
          url: '/api/common/user',
          data: {
            token: getNowToken()
          },

        }).then((res1) => {
          HttpGet({
            url: 'api/common/system/server/info',
            data: {
              sysId: '264',
            },
          }).then((response) => {
            let url = response.data.webSvrAddr + "/api/news/info//edit/detailed"
            HttpGet({
              url,
              data: {
                newsId: id,
              }
            }).then(res => {
              if (res.code == 200 && res.data) {
                let data = res.data
                console.log(data.newsCoverPath, 'data.newsCoverPath');

                setTitle(data.newsTitle)
                // setContent((data.newsContent).replace(/<[^>]*>|<\/[^>]*>/gm, ""))
                setContent(data.newsContent)
                setCover(JSON.parse(JSON.stringify(data.newsCoverPath)))
                setTypeId(data.newsTypeId)
                setTypeName(data.newsTypeName)
                let attachments = res.data.newsAttachmentVoList
                if (attachments && attachments.length !== 0) {
                  let imgArr = [], fileArr = [];
                  attachments.map(item => {
                    let fileType = Utils.getFileType(item?.attachmentName)
                    if (fileType == 'img') {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      imgArr.push(item)
                    } else {
                      item.url = item.attachmentUrl
                      item.size = item.attachmentSize
                      item.fileName = item.attachmentName
                      fileArr.push(item)
                    }
                  })

                  setFileList(fileArr)
                  setImgList(imgArr)
                }
                setIsRead(res.data.readStatus)
                setDetail(res.data)
              } else {
                Taro.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          })
        })
      }
    }
  }

  //获取全部类型
  const getTypeList = () => {
    let url = 'api/news/type/list'
    HttpGet({
      url,
      data: {
        eduId: userInfo.eduId
      }
    }).then((res) => {
      if (res.code == 200) {
        let data = res.data;
        data.forEach(item => {
          item.optionList = [
            { text: '编辑', onClick: () => operation('edit', item), className: 'edit' },
            { text: '删除', onClick: () => operation('del', item), className: 'delete' }]
        })
        setTypeList(data)
      }
    })
  }

  //上传图片
  const uploadImage = (type) => {
    let url = ''
    if (Utils.getSystemInfo() == 'weapp') {
      url = `api/commons/file/batch/upload`
      console.log(123)
    } else {
      url = baseUrl + `api/commons/file/batch/upload`
      // url = `api/commons/file/batch/upload`

      console.log(123456)
      console.log(storage.get('itemUrl'))
      // url =  getBaseUrl() +`api/commons/file/batch/upload`

    }
    let imgArr = imgList.concat([]);

    if (imgArr.length > 3) {
      Taro.showToast({
        title: '只能上传4张图片!',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    // if (Utils.getSystemInfo() == 'weapp') {
    //   url = Proxy.transmitUrlToVisit(baseUrl + url)
    // }
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFiles
        console.log(tempFilePaths, 'tempFilePaths');

        // imgList.push(tempFilePaths)
        const formData = new FormData();
        formData.append('files', tempFilePaths[0].originalFileObj);
        formData.append('modelName', 'newsInfoAppImage');
        Taro.showLoading({
          title: '正在上传~'
        })

        fetch(url, {
          method: 'POST',
          headers: {
            'Authorization': getToken() || getNowToken() || getQueryVariable('lg_tk')
          },
          body: formData
        })
          .then(response => response.json())
          .then(result => {
            const data = result.data;
            if (result.code == 200) {

              Taro.hideLoading();
              setTimeout(() => {
                Taro.showToast({
                  title: '上传成功'
                });
              }, 500);
              if (type == 'one') {
                imgArr.push(data[0]);
                setImgList(imgArr);
              } else {
                Taro.hideLoading();
                //选择封面
                setCover(data[0].url);
              }
              if ((imgArr.length + fileList.length) > 1) {
                setToEdu(false);
              }
            }
          })
          .catch(error => {
            Taro.hideLoading();
            setTimeout(() => {
              Taro.showToast({
                title: '上传失败',
                icon: 'none'
              });
            }, 500);
          });

        // HttpPost({
        //   url,
        //   data: formData,
        // }).then((data) => {
        //   if (data.code == 200) {
        //     Taro.hideLoading();
        //     setTimeout(() => {
        //       Taro.showToast({
        //         title: '上传成功'
        //       });
        //     }, 500);
        //     if (type == 'one') {
        //       imgArr.push(data[0]);
        //       setImgList(imgArr);
        //     } else {
        //       Taro.hideLoading();
        //       //选择封面
        //       setCover(data[0].url);
        //     }
        //     if ((imgArr.length + fileList.length) > 1) {
        //       setToEdu(false);
        //     }
        //   }
        // }).catch(error => {
        //   Taro.hideLoading();
        //   setTimeout(() => {
        //     Taro.showToast({
        //       title: '上传失败',
        //       icon: 'none'
        //     });
        //   }, 500);
        // });
      }
    })
  }
  // 删除文件/图片
  const deleteFile = (index, item, type) => {
    if (type == 'img') {
      let imgArr = imgList.concat([])
      imgArr.splice(index, 1)
      setImgList(imgArr)
    } else {
      let fileArr = fileList.concat([])
      fileArr.splice(index, 1)
      setFileList(fileArr)
    }
  }

  //上传文件
  const uploadSuccess = (res) => {
    let url = baseUrl + `api/commons/file/batch/upload`
    if (Utils.getSystemInfo() == 'weapp') {
      url = Proxy.transmitUrlToVisit(url)
    }
    let fileArr = fileList.concat([])
    if (fileArr.length > 3) {
      Taro.showToast({
        title: '只能上传4个文件!',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    const tempFilePaths = res.tempFiles
    if (tempFilePaths[0].size > 10 * 1024 * 1024) {
      Taro.showToast({
        title: '文件大小不能超过10MB！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    const token = getNowToken();
    let formData = new FormData();
    formData.append('files', tempFilePaths[0].originalFileObj);
    formData.append('modelName', 'newsInfoAppFiles');
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url);
    xhr.setRequestHeader('Authorization', token);
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          const result = JSON.parse(xhr.responseText);
          const data = result.data[0]
          if (result.code == '200') {
            Taro.showToast({
              title: '上传成功'
            })
            fileArr.push(data)
            setFileList(fileArr)
          }
          if ((imgList.length + fileArr.length) > 1) {
            setToEdu(false);
          }
        } else {
          Taro.hideLoading()
          setTimeout(() => {
            Taro.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }, 500);
        }
      }
    };
    xhr.upload.onprogress = function (e) {
      if (e.lengthComputable) {
        const percent = Math.round((e.loaded / e.total) * 100);
        Taro.showToast({
          icon: 'loading',
          title: `上传中${percent}%`,
          mask: true,
          duration: 10000
        })
      }
    };
    xhr.send(formData);
  }

  // 上传文件失败
  const uploadFail = () => {
    Taro.showToast({
      title: '上传失败请联系管理员',
      icon: 'none'
    })
  }

  //类型列表
  const handlePopLayer = (type, full = "") => {
    let arr = typeList.concat([])
    if (type == 'open') {
      setVisible(true)
    } else {
      setVisible(false)
    }
  }
  //选择类型
  const changeType = (obj, e) => {
    let target = e.target;
    if (target.classList.contains('edit') || target.classList.contains('delete')) {
      return;
    }
    setTypeId(obj.newsTypeId);
    setTypeName(obj.newTypeName);
    handlePopLayer('close')
  }

  //发布新闻资讯
  const createNotice = (sensitiveContent="") => {
    // if (title.length == 0) {
    //   Taro.showToast({
    //     title: '资讯标题不能为空！',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }
    // if (typeId == '') {
    //   Taro.showToast({
    //     title: '请选择类别！',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }
    // if (content.length == 0) {
    //   Taro.showToast({
    //     title: '请输入正文内容！',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return;
    // }
    let url = 'api/news/create/release';
    let arr = imgList.concat(fileList)
    let newsAttachmentVoList = []
    newsAttachmentVoList = arr.map(item => {
      let res = {}
      // res.attachmentUrl = item.url.indexOf('http://') == -1 ? item.url : item.url.slice((storage.get('itemUrl') || baseUrl).length, item.url.length),
      res.attachmentUrl = item.url,
        res.attachmentName = item.fileName
      res.attachmentSize = item.size
      return res;
    })
    Taro.showLoading({
      title: '正在发布~',
    })
    HttpPost({
      url,
      data: {
        newsId: newsId ? newsId : '',
        newsTitle: title,
        newsContent: sensitiveContent ? sensitiveContent : content,
        newsCoverPath: cover,
        userId: storage.get('UserID') || userInfo.userId,
        userName: storage.get('UserName') || userInfo.userName,
        eduId: userInfo.eduId,
        eduName: 'LG蓝鸽教育局',
        newsTypeId: typeId,
        newsAttachmentVoList,
        bePushEdu: toEdu && newsAttachmentVoList.length < 2 ? '1' : '0'
      }
    }).then((data) => {
      if (data.code == 200) {
        Taro.navigateBack({ delta: 1 })
        // Taro.redirectTo({
        //   url: `/pages/newsInfoApp/index`
        // })
        Taro.hideLoading();
        setTimeout(() => {
          Taro.showToast({
            title: '发布成功~',
            duration: 2000
          })
        }, 500);
      }
    })
  }

  //保存新闻资讯 2023-07-17
  const saveNotice = () => {
    if (title.length == 0) {
      Taro.showToast({
        title: '资讯标题不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (typeId == '') {
      Taro.showToast({
        title: '请选择类别！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (content.length == 0) {
      Taro.showToast({
        title: '请输入正文内容！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let url = 'api/news/create/save';
    let arr = imgList.concat(fileList)
    let newsAttachmentVoList = []
    newsAttachmentVoList = arr.map(item => {
      let res = {}
      // res.attachmentUrl = item.url.indexOf('http://') == -1 ? item.url : item.url.slice((storage.get('itemUrl') || baseUrl).length, item.url.length),
      res.attachmentUrl = item.url,
        res.attachmentName = item.fileName
      res.attachmentSize = item.size
      return res;
    })
    Taro.showLoading({
      title: '正在保存~',
    })
    console.log(userInfo)
    HttpPost({
      url,
      data: {
        newsId: newsId ? newsId : '',
        newsTitle: title,
        newsContent: content,
        newsCoverPath: cover,
        userId: storage.get('UserID') || userInfo.userId,
        userName: storage.get('UserName') || userInfo.userName,
        eduId: storage.get('schoolId') || userInfo.eduId,
        eduName: 'LG蓝鸽教育局',
        newsTypeId: typeId,
        newsAttachmentVoList,
      }
    }).then((data) => {
      if (data.code == 200) {
        Taro.navigateBack({ delta: 1 })
        // Taro.redirectTo({
        //   url: `/pages/newsInfoApp/index`
        // })
        Taro.hideLoading();
        setTimeout(() => {
          Taro.showToast({
            title: '保存成功~',
            duration: 2000
          })
        }, 500);
      }
    })
  }

  const showPreView = (item) => {
    let arr = [], url = item.url
    if (Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram') {
      url = replaceHost(url, baseUrl);
      imgList.map(t => {
        arr.push(replaceHost(t.url, baseUrl))
      })
    } else {
      imgList.map(t => {
        arr.push(t.url)
      })
    }

    Taro.previewImage({
      current: url, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  }

  // 操作常用设置
  const operation = (type, item) => {
    switch (type) {
      case 'edit': setOldValue(item.newTypeName), setInputPopOpen(true), setOldItem(item);
        break;
      case 'add': setOldValue(''), setOldItem(''), setInputPopOpenNew(true);
        break;
      case 'del':
        Taro.showModal({
          title: '是否删除该资讯类型？',
          content: '该类型下所有资讯也将被删除！',
          success: function (res) {
            if (res.confirm) {
              HttpDelete({
                url: '/api/news/type/delete?typeId=' + item.newsTypeId,
              }).then((result) => {
                if (result.code === '200') {
                  getTypeList();
                  Taro.showToast({
                    title: '删除成功',
                    duration: 2000,
                    mask: true
                  })
                }
              })
            } else if (res.cancel) {
              // console.log('用户点击取消')
            }
          }
        })
        break;
    }

  }

  const inputPop_confirmAdd = (value) => {
    if (!value) {
      console.log("输入值不能为空");
      Taro.showToast({ title: "类型名称不能为空", icon: 'none', duration: 1000 })
      return
    }

    let url = '/api/news/type/create'
    let data = {
      newTypeName: value,
      eduId: userInfo.eduId
    }
    HttpPost({
      url,
      data: data
    }).then((data) => {
      if (data.code == 200) {
        getTypeList();
        Taro.showToast({
          title: '添加成功',
          duration: 2000,
          mask: true
        })
      } else {
        Taro.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
      setInputPopOpen(false);
      setInputPopOpenNew(false);
    })
  }

  const inputPop_confirm = (value) => {
    if (!value) {
      console.log("输入值不能为空");
      Taro.showToast({ title: "类型名称不能为空", icon: 'none', duration: 1000 })
      return
    }
    if (value == oldItem.newTypeName) {
      Taro.showToast({ title: "请输入新的类型名称", icon: 'none', duration: 1000 })
      return
    }

    let url = '/api/news/type/update'
    let data = {
      newsTypeId: oldItem.newsTypeId,
      newTypeName: value,
      schoolId: userInfo.schoolId,
    }
    HttpPut({
      url,
      data: data
    }).then((data) => {
      if (data.code == 200) {
        getTypeList();
        Taro.showToast({
          title: '设置成功',
          duration: 2000,
          mask: true
        })
      } else {
        Taro.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
      setInputPopOpen(false);
      setInputPopOpenNew(false);
    })
  }

  const inputPop_cancel = () => {
    setInputPopOpen(false);
    setInputPopOpenNew(false);
    setOldValue('');
  }

  const goBack = () => {
    Taro.redirectTo({
      url: '/pages/newsInfoApp/index'
    })
  }

  const showFile = (item) => {
    browserController.openFileReader(storage.get(item.attachmentId))
  }

  const initWxSdk = async () => {
    const params = getWxSDKParams(['previewImage', 'getLocation'])
    wx.config(params);
    wx.ready(function () {
      // config信息验证后会执行 ready 方法，所有接口调用都必须在 config 接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在 ready 函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在 ready 函数中。
      console.log('ready')
    });
    wx.error(function (res) {
      // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
      console.log(res)
    });
  }

  // 获取敏感词
  const getSensetiveData = () => {
    HttpGet({
      url: "/api/sensitiveWord/list/word",
      data: {
        eduId: userInfo.eduId
      }
    }).then((res) => {
      if (res.code == 200) {
        // let data = res.data;
        setSensetiveData(Array.isArray(res.data) ? res.data : [])
      }
    })
  }

  const showSensetive = () => {
    if (title.length == 0) {
      Taro.showToast({
        title: '资讯标题不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (typeId == '') {
      Taro.showToast({
        title: '请选择类别！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (content.length == 0) {
      Taro.showToast({
        title: '请输入正文内容！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    let sensetiveWord = []
    let sensetiveEditorContent = content
    if (sensetiveData.length > 0) {
      sensetiveData.forEach((i, index) => {
        if (content.includes(i)) {
          sensetiveWord.push(i)
          const regex = new RegExp(i, 'g')
          sensetiveEditorContent = sensetiveEditorContent.replace(regex, "*")
        }
      })
    }
    console.log(sensetiveEditorContent)
    if (sensetiveWord.length > 0) {
      Dialog.show({
        content: <div>(强制发布敏感词内容会被替换为<span style={{ color: "red" }}>*</span>,并且会给管理员发送消息提醒)</div>,
        closeOnAction: true,
        title: <div>通知内容含有敏感词<span style={{ color: "red" }}>"{sensetiveWord.toString()}"</span>，确认是否发布？</div>,
        actions: [
          [
            {
              key: 'confirm',
              text: '确定',
              // bold: true,
            },
            {
              key: 'cancel',
              text: '再想想',
              // bold: true,
              danger: true,
            },
          ],
        ],
        onAction: (action) => {
          console.log(action)
          if (action.key == "confirm") {
            setContent(sensetiveEditorContent)
            createNotice(sensetiveEditorContent)
          }
        }
      })

    } else {
      createNotice()
    }
  }

  useEffect(() => {
    document.title = '创建部门资讯'
    if (window.__wxjs_environment == 'miniprogram') {
      initWxSdk()
    }
    getCommonData()
    getTypeList()
    getSensetiveData()
    return () => {
      if (Utils.getSystemInfo() == 'weapp') {
        document.title = '部门资讯'
        window.getNoticeList && typeof window.getNoticeList == 'function' && window.getNoticeList()
      }
    }
  }, []);

  const publishEdu = () => {
    setToEdu(!toEdu);
  }


  return (
    <View className="newsTitle">
      {
        Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram' ?
          "" :
          <Header
            className='header-top'
            mainTitle='创建部门资讯'
            mainTitleBlod={false}
            isTitlePositionLeft={true}
            needMainIcon={process.env.TARO_ENV == 'weapp' ? false : true}
            onClick={Taro.getCurrentInstance().router?.params.from ? goBack : ''}
          />
      }

      <View className="header">
        <LgInput
          value={title}
          maxLength={30}
          type="A"
          inputName={<Text><Text className='must-fill'>*</Text>标题</Text>}
          placeholder="输入部门资讯标题"
          onChange={value => setTitle(value)}
        ></LgInput>
        <View className='select_type'>
          <LgCell
            title={<Text><Text className='must-fill'>*</Text>类别</Text>}
            content={
              typeName ? typeName : '请选择'
            }
            showIcon={true}
            onClick={() => {
              handlePopLayer('open');
            }}
            type='A'
          ></LgCell>
          {/* 输入框弹窗 */}
          <PrPopInput
            oldValue={oldValue}
            title='重命名'
            isOpen={inputPopOpen}
            confirm={inputPop_confirm}
            cancel={inputPop_cancel}
            placeholder='请输入资讯类型标题…'
          ></PrPopInput>
          <PrPopInput
            title='创建资讯类型'
            isOpen={inputPopOpenNew}
            confirm={inputPop_confirmAdd}
            cancel={inputPop_cancel}
            placeholder='请输入资讯类型标题…'
          ></PrPopInput>
          <LgPopLayer
            position="bottom"
            confirm={() => { handlePopLayer('close',) }}
            showLayer={() => handlePopLayer('close',)}
            title={'类型选择'}
            showClose
            isOpen={visible}>
            {
              typeList.length < 12 ?
                <View>
                  <View className='type-add' onClick={() => operation('add', '')}>添加类型</View>
                  <View className='type-add-shu'>|</View>
                </View>
                : ''
            }
            {
              typeList.length > 0 ?
                typeList.map((item, index) => {
                  return (
                    <View className="kind_one" key={index} onClick={(e) => changeType(item, e)}>
                      <LgSlide data={item?.optionList} canSlide={true} key={visible + (item?.newsTypeId)}>
                        <View style={{ width: '100vw', marginRight: '18px' }}>
                          {item.newTypeName}
                        </View>
                      </LgSlide>
                    </View>
                  )
                }) : ''
            }
          </LgPopLayer>
          <View className="line"></View>
          <View className='cover_img'>
            <View className='title'>
              <Text className='must-fill' style={{ visibility: 'hidden' }}>*</Text>
              封面
            </View>
            <View className='right'>
              <View className='coverImg' style={{ backgroundImage: `url('${cover ? Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram' ? replaceHost(cover, baseUrl) : cover : ''}')` }} ></View>
              <Text className={'icon-b01901' + " icon"} onClick={() => uploadImage('cover')}></Text>
              {/* <Text className={'icon-b01901' + " icon"} onClick={() => Taro.chooseImage({ count: 1, success: coverImageSelect, fail: uploadFail, })}></Text> */}
            </View>
          </View>
          {
            systemInfo.beEdu == '1' ?
              <><View className="line"></View><View className='publish-edu'>
                <View className='title'>
                  发布至教育局<Text className='title-tip'>(同步到教育局端的资讯无法撤回,且只能上传一个附件)</Text>
                </View>
                <View className='right'>
                  <LgSwitch default={(imgList.length + fileList.length) > 1 ? false : toEdu}
                    disabled={(imgList.length + fileList.length) > 1 ? true : false} onClick={() => publishEdu()}></LgSwitch>
                </View>
              </View></>
              : ''
          }
        </View>
        <View className="mail_content">
          {/* <LgInput
            value={content}
            type="B"
            inputName={<Text><Text className='must-fill'>*</Text>正文</Text>}
            placeholder="请输入正文内容..."
            maxLength={10000}
            onChange={value => setContent(String(value))}
          ></LgInput> */}
          <MyEditor id='editor' getHtmlContent={(html) => { setContent(html && html !== '<p><br></p>' ? html : '') }}
            value={content} />
          <View className="line"></View>

        </View>
        <View className='upload'>
          <View className='upload_file upload_img' onClick={() => uploadImage('one')} >
          </View>
          <View className='upload_file upload_files' onClick={() => { Utils.chooseFile1({ count: 1, success: uploadSuccess, fail: uploadFail, }) }}>
          </View>
        </View>

        {
          <View className="attachment">
            <View className="imgBox">
              {
                imgList.map((item, index) => {
                  return (
                    <View className="imgItem">
                      <View className="imgSrc" style={{
                        backgroundImage: `url('${Utils.getQueryVariable('env') == 'weapp' || window.__wxjs_environment == 'miniprogram' ? replaceHost(item.url, baseUrl) : item.url}')`
                      }} onClick={() => showPreView(item)}></View>
                      <Text className="deletelogo" onClick={() => deleteFile(index, item, 'img')}></Text>
                    </View>
                  )
                })
              }
            </View>
            <View className="fileBox">
              {
                fileList.map((item, index) => {
                  let icon = Utils.getFileType(decodeURIComponent(item.fileName))
                  let fileIcon = {
                    "img": "0a00901",
                    "doc": "0a00101",
                    "ppt": "0a00201",
                    "pdf": "0a00501",
                    "txt": "0a00401",
                    "xls": "0a00301",
                    "music": "0a00601",
                    "video": "0a00701",
                    "html": "0a01001",
                    "zip": "0a01201",
                    "otr": "0a01101"
                  }
                  let src = fileObj[fileIcon[icon]]
                  // console.log(`fileObj`, fileObj['0a00101'])
                  // console.log(`src`, fileIcon[icon])
                  let size = Utils.getFileSize(item.size)
                  return (
                    <View className="docItem">
                      <View className="docIcon">
                        <Image className="docImg" src={src} />
                      </View>
                      <View className="docInfo">
                        <View className="docName oneline">{decodeURIComponent(item.fileName)}</View>
                        <View className="docSize">{size}</View>
                      </View>
                      <Text className="deletelogo" onClick={() => deleteFile(index, item, 'file')}></Text>

                      {/* {
                      (storage.get(item.attachmentId) || item.preView) ?
                        <View className="preViewFile" onClick={() => showFile(item)}>
                          <Text>查看</Text>
                        </View>
                        :
                        <View
                          className="downLoadIcon_content"
                          onClick={() => download(item, index)}
                          style={Utils.getNowEnvironment() ? { width: '32px', height: '32px' } : ''}
                        >
                        </View>

                    } */}

                    </View>
                  )
                })
              }
            </View>
          </View>
        }
      </View>

      <View className="index_footer">
        <LgButton className="send_btn" type='D' width={300} height={88} onClick={() => saveNotice()}> 保存</LgButton>
        <LgButton className="send_btn" type='B' width={300} height={88} onClick={() => showSensetive()} >发布</LgButton>
      </View>
    </View>
  )
}

const mainProps = ({ commonData }) => {
  // console.log(commonData, 'commonData');

  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl,
    systemInfo1: commonData.systemInfo,
  }
}

export default connect(mainProps)(App);
